//
//  TicketContentController.swift
//  ANOA
//
//  Created by 邱仙凯 on 2018/11/12.
//  Copyright © 2018 zwb. All rights reserved.
//

import UIKit
import SwiftyJSON
import IQKeyboardManager
class TicketContentController: UITableViewController,DateWidgetable {
    lazy var repeatV:TicketRepeatView = {
        let v = TicketRepeatView(frame: CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: KSGlobal.screenH))
        return v
    }()
    
    var id_key:String?        // 查看修改 传
    var refreshBlock:(()->())?
    var dataArray = [TContentStruct]() //  是否展开  数据模块  不同发票数据组   报销类型组 主图  辅助图
    var tkType = TkPhotoType.directLibrary
    
    static func initForImg(invoiceImage:UIImage,fCompany:Int,invoiceTypeCode:String? = nil,nameid:idAndName,refreshBlock:@escaping (()->())) -> TicketContentController { // 图片进入新增
        let vc = TicketContentController()
        vc.title = "新增发票"
        vc.tcVM.invoiceTypeCode = invoiceTypeCode.unwrap
        var picOne = PictureModel(json:"")
        picOne.img = invoiceImage
        picOne.isMain = "1"
        
        
        var one = TicketModel(json: "")
        one.fOrgNm = nameid.name
        one.fOrgId = nameid.id
        one.fCompany = fCompany
        one.fUseState = "未报销"
        
        let invoiceType = fCompany == 1 ? InvoiceType.zzs_normal_04 : InvoiceType.otherTax_00
        
        
        
        var picMainArr = [PictureModel]()
        picMainArr.append(picOne)
        let picArr2 = [PictureModel]()
        var tsOne = TContentStruct(openFlag: true, tkModel: one, performArray: [""], reimTypeArray: [""], picMainArr: picMainArr,picArr2:picArr2 )
        tsOne.tkModel.fInvoicetypeId = invoiceType
        tsOne.tkModel.fInvoicetypeNm = InvoiceType.code2Name(tsOne.tkModel.fInvoicetypeId.unwrap)
        vc.dataArray.append(tsOne)
        
        
        vc.refreshBlock = refreshBlock
        return vc
    }
    //  查验过带图进入新增 , 智能识别带多图进入新增 mainImages：发票图片 主图   assistfile:目前只有pdf类型
    static func initForImgModel(tkType:TkPhotoType,mainImages:[UIImage],assistfile:[[FileAssistModel]] = [] ,models:[TicketModel],fCompany:Int,invoiceTypeCode:String? = nil,nameid:idAndName,refreshBlock:@escaping (()->())) -> TicketContentController {
       
        let vc = TicketContentController()
        vc.title = "新增发票"
        vc.tcVM.invoiceTypeCode = invoiceTypeCode.unwrap
        vc.refreshBlock = refreshBlock
        vc.tkType = tkType
        
        for i in 0..<models.count {
            var openFlag = false
            if i == 0 {
                openFlag = true
            }
            let  defaultType = fCompany == 1 ? InvoiceType.zzs_normal_04 : InvoiceType.otherTax_00
            let invoiceType = models[i].fInvoicetypeId ?? defaultType
            
            var xone = models[i]
            xone.fCompany = fCompany
            xone.fOrgNm = nameid.name
            xone.fOrgId = nameid.id
            xone.fUseState = "未报销"
            
            var picOne = PictureModel(json:"")
            picOne.img = mainImages[i]
            picOne.isMain = "1"
            var picMainArr = [PictureModel]()
            picMainArr.append(picOne)
            
            let picArr2 = [PictureModel]()
            var fileArr = [FileAssistModel]()
            
         
           var assiA = [FileAssistModel]()
            if assistfile.count > i {
                assiA = assistfile[i]
            }
            
            var tsOne =  TContentStruct(openFlag: openFlag, tkModel: xone, performArray: [], reimTypeArray: [], picMainArr: picMainArr,picArr2:picArr2,files: assiA )
            
            tsOne.tkModel.fInvoicetypeId = invoiceType
            tsOne.tkModel.fInvoicetypeNm = InvoiceType.code2Name(tsOne.tkModel.fInvoicetypeId.unwrap)
            
            vc.dataArray.append(tsOne)
            
        }
        
        return vc
    }
    static func initForIdkey(invoiceTypeCode:String? = nil,id_key:String,title:String,refreshBlock:@escaping (()->())) -> TicketContentController { // idkey进入查看
        let vc = TicketContentController()
        vc.title = title
        vc.tcVM.invoiceTypeCode = invoiceTypeCode.unwrap
        vc.id_key = id_key
        vc.refreshBlock = refreshBlock
        return vc
    }
    lazy var header:BiaoQianView = {
        let header = BiaoQianView(frame:CGRect(x:0,y:0,width: KSGlobal.screenW,height: 40))
        return header
    }()
    
    
    var tcVM = TicketContentVM()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared().isEnableAutoToolbar = false
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared().isEnableAutoToolbar = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tcVM.vc = self
        // id_key 进来的一定是单条
        if id_key.isSome {
            
            KSNetwork.shared.fetchObjectAndPic(API.invoice(.getInvoice(id_key: "\(id_key!)", invoiceTypeCode: "\(tcVM.invoiceTypeCode)")), successHandle: { [weak self]  (data: TicketModel, picArr: [PictureModel], fileArr: [FileAssistModel]) in
                
                guard let `self` = self else {
                    return
                }
                
                var picMainArr = picArr.filter { $0.isMain == "1" }
//                for i in 0..<picMainArr.count {
//                    picMainArr[i].img = getPicture(url: configURL(latter: picMainArr[i].fUrl.unwrap))
//                }
                
                var picArr2 = picArr.filter { $0.isMain == "0" }
//                for i in 0..<picArr2.count {
//                    picArr2[i].img = getPicture(url: configURL(latter:picArr2[i].fUrl.unwrap))
//                }
                
                let invoiceType = data.fInvoicetypeId ?? InvoiceType.otherTax_00
                var tsOne = TContentStruct(openFlag: true,
                                           tkModel: data,
                                           performArray: [],
                                           reimTypeArray: [],
                                           picMainArr: picMainArr,
                                           picArr2: picArr2,
                                           files: fileArr)
                
                tsOne.tkModel.fInvoicetypeId = invoiceType
                tsOne.tkModel.fInvoicetypeNm = InvoiceType.code2Name(tsOne.tkModel.fInvoicetypeId.unwrap)
                
                self.dataArray.append(tsOne)
                self.initCompement()
                self.tableView.reloadData()
                
            }, errorHandle: nil)
        } else {
            
            
            self.initCompement()
            self.tableView.reloadData()
            
        }
        
    }
    private func initCompement() {
        self.tableView.tableFooterView = UIView()
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
         tableView.register(TicketImgCell.self, forCellReuseIdentifier: TicketImgCell.identifier)
        tableView.register(AssistImgCell.self, forCellReuseIdentifier: AssistImgCell.identifier)
        tableView.register(TicketDescCell.self, forCellReuseIdentifier: TicketDescCell.identifier)
        tableView.register(TicketNewComCell.self, forCellReuseIdentifier: TicketNewComCell.identifier)
     
        tableView.register(GlobalSectionHeader.self, forHeaderFooterViewReuseIdentifier: GlobalSectionHeader.identifier)
        tableView.separatorStyle = .none
        tableView.backgroundColor = Theme.commonBg
        tableView.showsVerticalScrollIndicator = false
        let rightBtn = UIButton.creat4Item(title: "保存") { _ in
            self.view.endEditing(true)
            
            self.prepare4Verify()
            
        }
        let right = UIBarButtonItem(customView: rightBtn)
        
        if self.dataArray.count > 0 , self.dataArray[0].tkModel.fUseState.unwrap == "未报销" {
            self.navigationItem.rightBarButtonItem = right
        } else {
            self.navigationItem.rightBarButtonItem = nil
        }
        
        header.field.text = self.dataArray.count > 0 ?  self.dataArray[0].tkModel.fLabel.unwrap : ""
        self.tableView.tableHeaderView = header
        
        let footerv = FootRoundView()
        tableView.tableFooterView = footerv
        
    }
    
    
    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        return dataArray.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        
        let tempArray = dataArray[section].performArray
        
        if dataArray[section].openFlag {
            return tempArray.count
        } else {
            return 0
        }
        
        
        
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let currentTModel = self.dataArray[indexPath.section].tkModel
        let tempArray = dataArray[indexPath.section].performArray
        let reimType = dataArray[indexPath.section].reimTypeArray
        let juSS = tempArray[indexPath.row]
        if tempArray[indexPath.row] == "基本信息" || tempArray[indexPath.row] == "发票照片" || tempArray[indexPath.row] == "辅助文件" {
            
            guard let cell = tableView.dequeueReusableCell(withIdentifier: TicketDescCell.identifier, for: indexPath) as? TicketDescCell else {
                fatalError()
            }
            cell.descLab.text = tempArray[indexPath.row]
            
            return cell
            
            
        } else if tempArray[indexPath.row] == "MainImg" {
            
            guard let cell = tableView.dequeueReusableCell(withIdentifier: TicketImgCell.identifier, for: indexPath) as? TicketImgCell else {
                fatalError()
            }
            cell.viewOnly = !editableJudge(currentTModel, rowName: juSS)
             
            
            if dataArray[indexPath.section].picMainArr.count > 0 {
                if let img = dataArray[indexPath.section].picMainArr[0].img {
                    cell.imageUtil?.showAllPicture(picS: [img])
                } else {
                    let urlss = [configURL(latter:(dataArray[indexPath.section].picMainArr[0].fUrl.unwrap))]
                    cell.imageUtil?.showPicture(urls: urlss, backImgs: { (imgA) in
                        if imgA.isSome {
                            self.dataArray[indexPath.section].picMainArr[0].img = imgA!.first
                        }
                        
                    })
                }
            }
            
            
            cell.deleteAction = { index in
                self.dataArray[indexPath.section].picMainArr.removeAll()
            }
            cell.addAction = { imgArr in
                imgArr.forEach {
                    var picOne = PictureModel(json:"")
                    picOne.fVouid = self.id_key.unwrap
                    picOne.isMain = "1"
                    picOne.img = $0
                    self.dataArray[indexPath.section].picMainArr.append(picOne)
                }
            }
            return cell
            
        } else if tempArray[indexPath.row] == "AssistImg" {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: AssistImgCell.identifier, for: indexPath) as? AssistImgCell else {
                fatalError()
            }
            if self.dataArray[indexPath.section].tkModel.fUseState.unwrap == "未报销" {
                cell.viewOnly = false
            } else {
                cell.viewOnly = true
            }
            
            
            
            var imgs = dataArray[indexPath.section].picArr2.compactMap { VideoImg(type:.image,image: $0.img )}
            
            if let filesss = dataArray[indexPath.section].files {
                imgs += filesss.compactMap { VideoImg(type: .file, idkey: $0.idKey.unwrap, num: $0.fNum, url: $0.fUrl, name: $0.fName, data: $0.fData) }
            }
            cell.imageUtil?.newestShow(arr: imgs)
            
            
            cell.deleteAction = { index in
                if index < self.dataArray[indexPath.section].picArr2.count {
                    self.dataArray[indexPath.section].picArr2.remove(at: index)
                } else {
                    if self.dataArray[indexPath.section].files.isSome {
                        self.dataArray[indexPath.section].files!.remove(at: index - self.dataArray[indexPath.section].picArr2.count)
                    }
                    
                }
                
            }
            // 添加了图片
            cell.addAction = { imgArr in
                imgArr.forEach {
                    var picOne = PictureModel(json:"")
                    picOne.fVouid = self.id_key.unwrap
                    picOne.isMain = "0"
                    picOne.img = $0
                    self.dataArray[indexPath.section].picArr2.append(picOne)
                }
                
            }
            // 添加了文件
            cell.addFileAction = { files in
                var filesss = [FileAssistModel]()
                files.forEach {
                    let one = FileAssistModel(json:"")
                    one.fName = $0.name
                    one.fNum = "\(indexPath.section)"
                    one.fData = $0.data
                    one.fUrl = $0.url
                    one.idKey = $0.idkey
                    KSLog("详情页选择文件")
                    KSLog($0.url)
                    filesss.append(one)
                }
                if self.dataArray[indexPath.section].files.isSome {
                    self.dataArray[indexPath.section].files! += filesss
                } else {
                    self.dataArray[indexPath.section].files = filesss
                    
                }
            }
            
            
            
            return cell
            
            
        } else {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: TicketNewComCell.identifier, for: indexPath) as? TicketNewComCell else {
                fatalError()
            }
            cell.titleLab.text = tempArray[indexPath.row]
            cell.showStatusDeal(currentTModel, rowName: juSS)
             if tempArray[indexPath.row] == "发票类型" {
              
               
               cell.contentLab.text = currentTModel.fInvoicetypeNm.unwrap
             
               cell.setTicketTextColor(Theme.textColor())
                
                cell.assistBtn.setBackgroundImage(UIImage(named: "formitem_right"), for: .normal)
               
               
           } else if tempArray[indexPath.row] == "报销类型" {
               
               cell.contentLab.text = currentTModel.fBxtypeNm
             
               cell.setTicketTextColor(Theme.textColor())
 
               
               
           } else if tempArray[indexPath.row] == "公司名称" {
                
               cell.contentLab.text = currentTModel.fOrgNm
      
               cell.setTicketTextColor(Theme.textColor())
 
               
               
           } else if tempArray[indexPath.row] == "发票日期" {
               
               cell.contentLab.text = currentTModel.fInvoicedate
                cell.setTicketTextColor(Theme.textColor())
 
               
           } else if tempArray[indexPath.row] == "报销状态" {
                
               cell.contentLab.text = self.dataArray[indexPath.section].tkModel.fUseState.unwrap
                cell.setTicketTextColor(Theme.primaryColor())
 
               
           } else if tempArray[indexPath.row] == "查验状态" {
                
               cell.contentLab.text = checkStatusStr(one: currentTModel)
                cell.setTicketTextColor(Theme.primaryColor())
 
               
           } else if tempArray[indexPath.row] == "发票金额" || tempArray[indexPath.row] == "价税合计" {
           
               cell.contentLab.text = self.dataArray[indexPath.section].tkModel.fTotalamount.unwrap
                 cell.contentLab.addTextEditEndClosure { field in
                   let str = field.text.unwrap
                   if isPurnFloat(string: str) {
                       self.dataArray[indexPath.section].tkModel.fTotalamount = str
                   } else {
                       KSToast("不是合法数字")
                       self.dataArray[indexPath.section].tkModel.fTotalamount = nil
                       cell.contentLab.text = ""
                   }
               }
            
               
           }  else if tempArray[indexPath.row] == "税额"  {
                
               cell.contentLab.text = self.dataArray[indexPath.section].tkModel.fTaxamount.unwrap
                 cell.contentLab.addTextEditEndClosure { field in
                   let str = field.text.unwrap
                   if isPurnFloat(string: str) {
                       self.dataArray[indexPath.section].tkModel.fTaxamount = str
                   } else {
                       KSToast("不是合法数字")
                       self.dataArray[indexPath.section].tkModel.fTaxamount = nil
                       cell.contentLab.text = ""
                   }
               }
            
               
           } else if tempArray[indexPath.row] == "金额(不含税)"  {
                
               cell.contentLab.text = self.dataArray[indexPath.section].tkModel.fInvoiceamount.unwrap
                 cell.contentLab.addTextEditEndClosure { field in
                   let str = field.text.unwrap
                   if isPurnFloat(string: str) {
                       self.dataArray[indexPath.section].tkModel.fInvoiceamount = str
                   } else {
                       KSToast("不是合法数字")
                       self.dataArray[indexPath.section].tkModel.fInvoiceamount = nil
                       cell.contentLab.text = ""
                   }
               }
           
               
               
           } else if tempArray[indexPath.row] == "税率(%)"  {
               
               cell.contentLab.text = self.dataArray[indexPath.section].tkModel.fTaxRate.unwrap
               cell.contentLab.addTextEditEndClosure { field in
                   let str = field.text.unwrap
                   if isPurnFloat(string: str) {
                       self.dataArray[indexPath.section].tkModel.fTaxRate = str
                   } else {
                       KSToast("不是合法数字")
                       self.dataArray[indexPath.section].tkModel.fTaxRate = nil
                       cell.contentLab.text = ""
                   }
               }
           
               
               
           } else if tempArray[indexPath.row] == "发票代码"  {
                
               cell.contentLab.text = self.dataArray[indexPath.section].tkModel.fInvoicecode.unwrap
                 cell.contentLab.addTextEditEndClosure { field in
                   let str = field.text.unwrap
                  
                   self.dataArray[indexPath.section].tkModel.fInvoicecode = str
                
               }
            
               
           } else if tempArray[indexPath.row] == "发票号码"  {
                
               cell.contentLab.text = self.dataArray[indexPath.section].tkModel.fInvoiceno.unwrap
                 cell.contentLab.addTextEditEndClosure { field in
                   let str = field.text.unwrap
                    self.dataArray[indexPath.section].tkModel.fInvoiceno = str
                }
            
               
           }  else if tempArray[indexPath.row] == "始发站" || tempArray[indexPath.row] == "入口" || tempArray[indexPath.row] == "出发城市"  {
                
               cell.contentLab.text = self.dataArray[indexPath.section].tkModel.fDepartcity.unwrap
                 cell.contentLab.addTextEditEndClosure { field in
                   let str = field.text.unwrap
                    self.dataArray[indexPath.section].tkModel.fDepartcity = str
                }
            
               
           }  else if tempArray[indexPath.row] == "终点站" || tempArray[indexPath.row] == "出口" || tempArray[indexPath.row] == "到达城市"  {
                
               cell.contentLab.text = self.dataArray[indexPath.section].tkModel.fArrivecity.unwrap
                 cell.contentLab.addTextEditEndClosure { field in
                   let str = field.text.unwrap
                    self.dataArray[indexPath.section].tkModel.fArrivecity = str
                }
            
               
           }  else if tempArray[indexPath.row] == "车次/航班" {
          
               cell.contentLab.text = self.dataArray[indexPath.section].tkModel.fTrainnumber.unwrap
                 cell.contentLab.addTextEditEndClosure { field in
                   let str = field.text.unwrap
                    self.dataArray[indexPath.section].tkModel.fTrainnumber = str
                }
            
               
           }  else if tempArray[indexPath.row] == "购买方" {
                
               cell.contentLab.text = self.dataArray[indexPath.section].tkModel.fBuyername.unwrap
                 cell.contentLab.addTextEditEndClosure { field in
                   let str = field.text.unwrap
                    self.dataArray[indexPath.section].tkModel.fBuyername = str
                }
            
               
           }  else if tempArray[indexPath.row] == "购买方税号" {
                
               cell.contentLab.text = self.dataArray[indexPath.section].tkModel.fBuyertaxno.unwrap
                 cell.contentLab.addTextEditEndClosure { field in
                   let str = field.text.unwrap
                    self.dataArray[indexPath.section].tkModel.fBuyertaxno = str
                }
            
               
           } else if  tempArray[indexPath.row] == "销售方" {
             
               cell.contentLab.text = self.dataArray[indexPath.section].tkModel.fSalername.unwrap
                 cell.contentLab.addTextEditEndClosure { field in
                   let str = field.text.unwrap
                    self.dataArray[indexPath.section].tkModel.fSalername = str
                }
            
               
           } else if  tempArray[indexPath.row] == "销售方税号" {
          
               cell.contentLab.text = self.dataArray[indexPath.section].tkModel.fSalertaxno.unwrap
                 cell.contentLab.addTextEditEndClosure { field in
                   let str = field.text.unwrap
                    self.dataArray[indexPath.section].tkModel.fSalertaxno = str
                }
            
               
           } else  if tempArray[indexPath.row] == "服务名称" {
            
 
               if currentTModel.details == nil {
                   let arr = [TicketDetailModel]()
                   dataArray[indexPath.section].tkModel.details = arr
                   let det = TicketDetailModel(json:"")
                   dataArray[indexPath.section].tkModel.details?.append(det)
               }
               if var detail = dataArray[indexPath.section].tkModel.details?.first  {
                   cell.contentLab.text = self.dataArray[indexPath.section].tkModel.details![0].fGoodsname.unwrap
    
                   cell.contentLab.addTextEditEndClosure { field in
                       self.dataArray[indexPath.section].tkModel.details![0].fGoodsname = field.text
                   }
               }
          
           } else if tempArray[indexPath.row] == "备注" {
         
               cell.contentLab.text = self.dataArray[indexPath.section].tkModel.fRemark.unwrap
                 cell.contentLab.addTextEditEndClosure { field in
                   let str = field.text.unwrap
                    self.dataArray[indexPath.section].tkModel.fRemark = str
                }
            
               
               
           } else if  tempArray[indexPath.row] == "校验码末6位" ||
                       tempArray[indexPath.row] == "数电票号码末6位" {
           
 
                   if dataArray[indexPath.section].tkModel.fVerifycode.isSome {
                       if dataArray[indexPath.section].tkModel.fVerifycode!.count > 6 {
                           cell.contentLab.text = String(currentTModel.fVerifycode!.suffix(6))
                       } else {
                           cell.contentLab.text  = currentTModel.fVerifycode!
                       }
                   } else {
                       cell.contentLab.text = ""
                   }
               cell.contentLab.addTextEditEndClosure { field in
                   self.dataArray[indexPath.section].tkModel.fVerifycode = field.text
                   }
   
           
               
               
               
           }
            return cell
        }
        
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let tempArray = dataArray[indexPath.section].performArray
        let reimType = dataArray[indexPath.section].reimTypeArray
        let currentTModel = self.dataArray[indexPath.section].tkModel

        let juSS = tempArray[indexPath.row].replacingOccurrences(of: ":", with: "")
        guard editableJudge(currentTModel, rowName: juSS) else {
             return
        }
        if tempArray[indexPath.row] == "发票类型" {
             
            
            var items = [""]
            if self.dataArray[indexPath.section].tkModel.fCompany.intWrap == 1 {
                items = invoiceComArr
            } else {
                items = invoiceNameArr()
            }
            
            let cle:(nameAndModel<String>)->() = { one in
                
                var invoiceType = InvoiceType.otherTax_00
                for (key,value ) in InvoiceType.invoiceCode2Name {
                    if value == one.model {
                        invoiceType = key
                        self.dataArray[indexPath.section].tkModel.fInvoicetypeId = invoiceType
                        self.dataArray[indexPath.section].tkModel.fInvoicetypeNm = InvoiceType.code2Name(invoiceType)
                    }
                }
                
                self.tableView.reloadData()
                
            }
            var allArr = [nameAndModel<String>]()
            for item in items {
                let one = nameAndModel(shows: [item], model: item)
                allArr.append(one)
            }
            let vc = KSSingleSelectUtil.initWithNav(title: "选择", allArr: allArr, backClosure: cle)
            self.present_FullScreen(to: vc)
        }
        if tempArray[indexPath.row] == "报销类型" {
          
            
            let cle:(nameAndModel<String>)->() = { one in
                
                for (key,value ) in reimbType {
                    if value == one.model {
                        self.dataArray[indexPath.section].tkModel.fBxtypeId = Int(key)!
                        self.dataArray[indexPath.section].tkModel.fBxtypeNm = value
                    }
                }
                
                self.tableView.reloadData()
                
            }
            var allArr = [nameAndModel<String>]()
            for item in reimType {
                let one = nameAndModel(shows: [item], model: item)
                allArr.append(one)
            }
            let vc = KSSingleSelectUtil.initWithNav(title: "选择", allArr: allArr, backClosure: cle)
            self.present_FullScreen(to: vc)
            
            
            
        }
        if tempArray[indexPath.row] == "公司名称" {
           
            let nameA = USERINFO.managredUnitNm!.components(separatedBy:",")
            let idA = USERINFO.managredUnit!.components(separatedBy: ",")
            
            
            let cle:(nameAndModel<String>)->() = { one in
                
                for i in 0..<nameA.count {
                    if nameA[i] == one.model {
                        self.dataArray[indexPath.section].tkModel.fOrgNm = one.model
                        self.dataArray[indexPath.section].tkModel.fOrgId = idA[i]
                        
                    }
                }
                
                self.tableView.reloadData()
                
            }
            var allArr = [nameAndModel<String>]()
            for item in nameA {
                let one = nameAndModel(shows: [item], model: item)
                allArr.append(one)
            }
            let vc = KSSingleSelectUtil.initWithNav(title: "选择", allArr: allArr, backClosure: cle)
            self.present_FullScreen(to: vc)
            
        }
        
        
        
        
        
        
        
        if tempArray[indexPath.row] == "发票日期" {
          
            self.showDateSelect(self) { str in
                self.dataArray[indexPath.section].tkModel.fInvoicedate = str
                self.tableView.reloadData()
            }
            
        }
 
        
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let tempArray = dataArray[indexPath.section].performArray
        
        if tempArray[indexPath.row] == "基本信息" || tempArray[indexPath.row] == "发票照片" || tempArray[indexPath.row] == "辅助文件" {
            return 38
        } else if tempArray[indexPath.row] == "MainImg" || tempArray[indexPath.row] == "AssistImg"  {
            return 120
      
        }  else {
            return 42
        }
        
        
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 60
    }
 
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        
        let sectionHeaderView = tableView.dequeueReusableHeaderFooterView(withIdentifier: GlobalSectionHeader.identifier) as! GlobalSectionHeader
        sectionHeaderView.roundMode = .alwaysRound
        let tap = UITapGestureRecognizer()
        tap.numberOfTapsRequired = 1
        tap.addTap { [unowned self] _ in
            self.dataArray[section].openFlag = !self.dataArray[section].openFlag
            let set = IndexSet(integer:section)
            tableView.reloadSections(set, with:UITableView.RowAnimation.automatic)
            
        }
        
        sectionHeaderView.addGestureRecognizer(tap)
        
        
        
        
        
        var titleStr = ""
                if self.dataArray[section].tkModel.errorMsg.unwrap == "" {
                    titleStr = self.dataArray[section].tkModel.fInvoicetypeNm.unwrap
                } else {
                    // 有出错信息时，显示在标题上，背景红色
                    titleStr = "\(self.dataArray[section].tkModel.fInvoicetypeNm.unwrap)(\(self.dataArray[section].tkModel.errorMsg.unwrap))"
                 }

        
        sectionHeaderView.setTitle(titleStr)
        if self.dataArray.count > 1 {
            sectionHeaderView.delBtn.isHidden = false
            sectionHeaderView.delBtn.tag = section
            sectionHeaderView.delBtn.addTouchUpInSideAction{ sender in
                alertUtil(self, title: "确定删除第\(sender.tag + 1)张发票", operateS: [nameAction(name: "确定", action: { [unowned self] (_) in
                    self.dataArray.remove(at: sender.tag)
                    self.tableView.reloadData()
                })])
            }

        } else {
            sectionHeaderView.delBtn.isHidden = true
        }
        
 
        sectionHeaderView.setOpenx(flag: self.dataArray[section].openFlag)

   
        return sectionHeaderView
        
    }
    
    
    
    
     
    
    
    
    
    
    
    
    //校验表单之前数处理，加标签 加序号  把细表赋值上等
    func prepare4Verify() {
        
        var verifyFlag = true
        for i in 0..<self.dataArray.count {
            
            // 把标签加上
            self.dataArray[i].tkModel.fLabel = header.field.text
            
            
            // 细表的金额要一起赋值一下
            if self.dataArray[i].tkModel.details == nil || self.dataArray[i].tkModel.details?.count == 0 {
                let arr = [TicketDetailModel]()
                self.dataArray[i].tkModel.details = arr
                self.dataArray[i].tkModel.details?.append(TicketDetailModel(json:""))
            }
            self.dataArray[i].tkModel.details![0].fDetailamount = self.dataArray[i].tkModel.fTotalamount.unwrap
            
            
            
            
            
            
            let  result = verifyOneModel(self.dataArray[i].tkModel, picMainArr: self.dataArray[i].picMainArr, picArr2: self.dataArray[i].picArr2, files: self.dataArray[i].files,index: i + 1)
            verifyFlag = result
            if verifyFlag {
                continue
            } else {
                break
            }
        }
        if verifyFlag {  // 全部内容合法性校验通过
            if self.dataArray.count == 1 { // 单张
                
                
                self.dataArray[0].tkModel.fIseinvoice = isElectronicInvoice(self.dataArray[0].tkModel)
                
                
                
                self.checkInvoiceIfnecessary(self.dataArray.first!.tkModel,picMainArr: self.dataArray.first!.picMainArr,picArr2: self.dataArray.first!.picArr2, files: self.dataArray.first!.files,invoiceTypeCode:self.tcVM.invoiceTypeCode)
            } else { // 多张
                
                for i in 0..<self.dataArray.count { // 配置序号，可以接收返回的错误
                    self.dataArray[i].tkModel.fpNumber = "\(i)"
                    
                    self.dataArray[i].tkModel.fIseinvoice = isElectronicInvoice(self.dataArray[i].tkModel)
                    
                }
                
                tcVM.saveMutiContinue(self.dataArray)
                
                
                
                
            }
        }
        
    }
    
    
    
    // MARK: - 校验事件   index 第几张，索引加1
    func verifyOneModel(_ origOne:TicketModel,picMainArr:[PictureModel],picArr2:[PictureModel],files:[FileAssistModel]?,index:Int) -> Bool {
        
        var one_e = origOne
        
        guard one_e.fTotalamount.isSome && doubleTran(one_e.fTotalamount) != 0 else {
            KSToast("第\(index)张发票金额不为空,不为0")
            return false
        }
        
        if mustJudge(one_e, rowName: "发票号码") {
            guard one_e.fInvoiceno.isSome else {
                KSToast("第\(index)张发票号码不为空")
                return false
            }
        }
        if mustJudge(one_e, rowName: "发票代码") {
            guard one_e.fInvoicecode.isSome,!(one_e.fInvoicecode.unwrap.isEmpty) else {
                KSToast("第\(index)张发票代码不为空")
                return false
            }
        }
   
          if  mustJudge(one_e, rowName: "服务名称") {
            let det = one_e.details![0]
            guard det.fGoodsname.isSome,!(det.fGoodsname.unwrap.isEmpty) else {
                KSToast("第\(index)张服务名称不为空")
                return false
            }
            
        }
        
         if  mustJudge(one_e, rowName: "金额(不含税)")  {
             guard one_e.fInvoiceamount.isSome && doubleTran(one_e.fInvoiceamount) != 0 else {
                KSToast("第\(index)张金额(不含税)不为空")
                return false
            }
        }
        
        
        if  mustJudge(one_e, rowName: "出发城市") {
            guard one_e.fDepartcity.unwrap != "" else {
                KSToast("第\(index)张出发城市不为空")
                return false
            }
        }
        if  mustJudge(one_e, rowName: "到达城市") {
            guard one_e.fArrivecity.unwrap != "" else {
                KSToast("第\(index)张到达城市不为空")
                return false
            }
        }
        if  mustJudge(one_e, rowName: "车次/航班") {
            guard one_e.fTrainnumber.unwrap != "" else {
                KSToast("第\(index)张车次/航班不为空")
                return false
            }
        }
        if  mustJudge(one_e, rowName: "始发站")  {
            guard one_e.fDepartcity.unwrap != "" else {
                KSToast("第\(index)张始发站不为空")
                return false
            }
        }
        if  mustJudge(one_e, rowName: "终点站")  {
            guard one_e.fArrivecity.unwrap != "" else {
                KSToast("第\(index)张终点站不为空")
                return false
            }
            
        }
        if mustJudge(one_e, rowName: "入口") {
            guard one_e.fDepartcity.unwrap != "" else {
                KSToast("第\(index)张入口不为空")
                return false
            }
        }
        if mustJudge(one_e, rowName: "出口") {
            guard one_e.fArrivecity.unwrap != "" else {
                KSToast("第\(index)张出口不为空")
                return false
            }
            
        }
        guard picMainArr.count == 1 else {
            KSToast("第\(index)张发票图片不能为空")
            return false
        }
        return true
        
    }
    
    // 单张才会执行的 查验并保存
    func checkInvoiceIfnecessary(_ origOne:TicketModel,picMainArr:[PictureModel],picArr2:[PictureModel],files:[FileAssistModel]?,invoiceTypeCode:String) {
        
        if tkType == .takePhoto4Intelligent || tkType == .library4Interlligent {
            alertUtil(title: "智能识别受发票清晰度、图片质量等客观因素影响可能会识别错误，请务必仔细核对发票信息后再保存", operateS: [nameAction(name: "确定", action: { _ in
                self.tcVM.ticketSaveContinue(tkType:self.tkType,one:origOne, picMainArr: picMainArr, picArr2: picArr2,files:files , cTitle: self.title!)
             })])
        } else {
            tcVM.ticketSaveContinue(tkType:tkType,one:origOne, picMainArr: picMainArr, picArr2: picArr2,files:files , cTitle: self.title!)
        }
        
       
        
    }
    
}




